package com.pulisher.controller;

import com.pulisher.bean.TrafficSourceBean;
import com.pulisher.service.TrafficStatsService;
import com.pulisher.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController
public class TrafficStatsController {
    @Autowired
    private TrafficStatsService trafficStatsService;

    @RequestMapping("/source")
    public String getSource(@RequestParam(value = "date",defaultValue = "0") Integer date){
        if (date == 0){
            date = DateFormatUtil.now();
        }
        List<TrafficSourceBean> source = trafficStatsService.getSource(date);

        StringBuilder json =new StringBuilder("{\"status\": 0,\"data\": {\"indicators\": [\n" +
                "      {\"text\": \"独立访客数\",\"max\": 300},\n" +
                "      {\"text\": \"会话总数\",\"max\": 110},\n" +
                "      {\"text\": \"会话平均浏览页面\",\"max\": 30},\n" +
                "      {\"text\": \"会话平均停留时间\",\"max\": 2100000},\n" +
                "      {\"text\": \"跳出率\",\"max\": 1}],\n" +
                "    \"series\": [");
        for (int i = 0; i < source.size(); i++) {
            TrafficSourceBean trafficSourceBean = source.get(i);
            if (trafficSourceBean != null) {
                String sourceSite = trafficSourceBean.getSource_site();
                BigDecimal uuCt = trafficSourceBean.getUu_ct();
                BigDecimal sidCt = trafficSourceBean.getSid_ct();
                BigDecimal avgPageView = trafficSourceBean.getAvg_page_view();
                BigDecimal avgDurtime = trafficSourceBean.getAvg_dur_time();
                BigDecimal br = trafficSourceBean.getBr();
                json.append("      {\n" +
                        "        \"name\": \"" + sourceSite + "\",\n" +
                        "        \"value\": [\n" +
                        "          " + uuCt + ",\n" +
                        "          " + sidCt + ",\n" +
                        "          " + avgPageView + ",\n" +
                        "          " + avgDurtime + ",\n" +
                        "          " + br + "\n" +
                        "        ]\n" +
                        "      }");
                if (i < source.size() - 1) {
                    json.append(",");
                }
            }
        }
        json.append("]\n" +
                "  }\n" +
                "}");

        return json.toString();
    }
}
